package com.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xutils.http.body.InputStreamBody;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class DownLoadTool extends AsyncTask<String, Void, String>{
	DownLoadCallBack downLoadCallBack;
	String path;
	public DownLoadTool(DownLoadCallBack downLoadCallBack) {
		this.downLoadCallBack = downLoadCallBack;
	}
	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		String result = "失败";
		FileOutputStream out  = null;
		InputStream inputStream = null;
		try {
			File file = new File(Environment.getExternalStorageDirectory() + "/fireHome");
			if (!file.exists()) {
				boolean flag =file.mkdirs();
				
				Log.e("flag", ""+flag );
			}
			 
			  
		    String fileName = params[0].trim().substring(params[0].trim().lastIndexOf("/")+1);  
			file = new File(file.toString() +"/"+ fileName);
			Log.e("file", "" + file.toString());
			path = file.toString();
			file.delete();
			file.createNewFile();
			
			 URL url = new URL(params[0]);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setDoInput(true);
             connection.connect();

             out = new FileOutputStream(file);
             
             
             if (connection.getResponseCode() == 200) {
            	 inputStream = connection.getInputStream();
            	 Log.e("inputStream=", "" + connection.getContentLength());
            	 byte[] b = new byte[1024];
            	 int m = -1;
            	 while((m = inputStream.read(b)) > 0){
            		 out.write(b, 0,m);
            	 }
            	
            	 result = "成功";
             }
			
		} catch (Exception e) {
			e.printStackTrace();
			result =  "失败";
		}finally{
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			
		}
		return result;
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		
		downLoadCallBack.onBack("成功".equals(result),path);
	}
	
	public interface DownLoadCallBack{
		void onBack(boolean result,String path);
	}
}
